var prefix = '';

var handleKey = function handleKey(key) {
  return "".concat(prefix, "_").concat(key);
};

function setPrefix(value) {
  prefix = value;
}

function getStorage() {
  var local = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
  return local ? window.localStorage : window.sessionStorage;
}

function set(key, value) {
  var local = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;

  if (key && value) {
    try {
      var valueString;

      if (value instanceof Array || value instanceof Object) {
        valueString = JSON.stringify(value);
      } else {
        valueString = value;
      }

      getStorage(local).setItem(handleKey(key), valueString);
      return true;
    } catch (e) {
      return false;
    }
  } else {
    return false;
  }
}

function get(key) {
  var local = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;

  if (key) {
    var value = null;

    try {
      var valueString = getStorage(local).getItem(handleKey(key));
      value = valueString;
      var firstChar = valueString && valueString.length > 1 ? valueString.charAt(0) : null;

      if (firstChar === '{' || firstChar === '[') {
        return JSON.parse(valueString);
      }

      return valueString;
    } catch (e) {
      return value;
    }
  } else {
    return null;
  }
}

function remove(key) {
  var local = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  return getStorage(local).removeItem(handleKey(key));
}

function setAsync(key, value) {
  var local = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
  return new Promise(function (resolve) {
    resolve(set(key, value, local));
  });
}

function getAsync(key) {
  var local = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  return new Promise(function (resolve) {
    resolve(get(key, local));
  });
}

function removeAsync(key) {
  var local = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  return new Promise(function (resolve) {
    resolve(getStorage(local).removeItem(handleKey(key)));
  });
}

export { setPrefix, set, get, remove, setAsync, getAsync, removeAsync };
export default {
  setPrefix: setPrefix,
  set: set,
  get: get,
  remove: remove,
  setAsync: setAsync,
  getAsync: getAsync,
  removeAsync: removeAsync
};